package com.netty.client;

import io.netty.bootstrap.Bootstrap;
import io.netty.channel.Channel;
import io.netty.channel.ChannelFuture;
import io.netty.channel.ChannelInitializer;
import io.netty.channel.ChannelOption;
import io.netty.channel.ChannelPipeline;
import io.netty.channel.nio.NioEventLoopGroup;
import io.netty.channel.socket.SocketChannel;
import io.netty.channel.socket.nio.NioSocketChannel;
import io.netty.handler.timeout.IdleStateHandler;

public class NettyClient {

	public int readerIdleTimeSeconds = 10;
	public int writerIdleTimeSeconds = 10;
	public int allIdleTimeSeconds = 30;
	public Channel channel;
	
	public void start(){
		Bootstrap bootstrap = new Bootstrap();
		NioEventLoopGroup group = new NioEventLoopGroup();
		bootstrap.group(group);
		bootstrap.option(ChannelOption.SO_KEEPALIVE, true);
		bootstrap.channel(NioSocketChannel.class);
		bootstrap.handler(new ChannelInitializer<SocketChannel>() {

			@Override
			protected void initChannel(SocketChannel channel) throws Exception {
				ChannelPipeline pipeline = channel.pipeline();
				pipeline.addLast("idle", new IdleStateHandler(readerIdleTimeSeconds, writerIdleTimeSeconds, allIdleTimeSeconds));
				pipeline.addLast("decoder", new NettyDecoder());
				pipeline.addLast("handler", new NettyHandler());
				pipeline.addLast("encoder", new NettyEncoder());
			}
			
		});
		try {
			ChannelFuture future = bootstrap.connect("localhost", 11230).sync();
			channel = future.channel();
			future.channel().closeFuture().sync();
		} catch (InterruptedException e) {
			e.printStackTrace();
		} finally {
			group.shutdownGracefully();
		}
	}
	
	public static void main(String[] args) throws Exception {
		final NettyClient client = new NettyClient();
		new Thread(){
			public void run() {
				client.start();
			};
		}.start();
		Thread.sleep(3000);
		while (true) {
			client.channel.writeAndFlush("=> ".getBytes());
			Thread.sleep(3000);
		}
	}
}
